module.exports = function httpdemo() {
    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;
    const Agent = http.Agent;

    if (cluster.isMaster) {
        console.log(`主进程 ${process.pid} 正在运行`);

        // 衍生工作进程。
        for (let i = 0; i < numCPUs; i++) {
            cluster.fork();
        }

        cluster.on('exit', (worker, code, signal) => {
            console.log(`工作进程 ${worker.process.pid} 已退出`);
        });

        cluster.on("fork", (worker) => { // 创建进程
            console.log(worker.id);
        });

        cluster.on('listening', (worker, address) => {
            var postData = "这是一些数据";
            var req = http.request({ // 设置并创建客户端连接
                hostname: 'localhost',
                port: 8000,
                path: '/',
                method: "POST",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(postData)
                },
                agent: false  // 仅为此一个请求创建一个新代理。
            }, (res) => {
                res.on("data", (data) => { // 监听数据
                    console.log("客户端: "+data.toString());
                })
            });
            req.write(postData);
            req.end();
        });

        // cluster.disconnect(() => { // 会导致进程结束
        //     console.log("end of all cluster");
        // })
    } else {
        http.createServer((req, res) => { // 创建http服务器
            console.log("server has been called.")
            res.writeHead(206);
            res.write("hello,world");
            res.end('你好世界\n');

            req.on("data", function (data) { // 监听客户端数据
                console.log("服务端: "+data.toString());
            })
        }).listen(8000);

        console.log(`工作进程 ${process.pid} 已启动`);
    }
}